import fs from "fs/promises";

interface Data {
  his: Record<string, any>;
  coins: Record<string, boolean>;
  settings: Record<string, boolean>;
  chats: Record<string, any>;
}

let data: Data = {
  his: {},
  coins: {},
  settings: {},
  chats: {},
};

async function initData() {
  try {
    const fileContent = await fs.readFile("./data.json");
    data = JSON.parse(fileContent.toString());

    data.coins = data.coins || {};
    data.his = data.his || {};
    data.settings = data.settings || {};
    data.chats = data.chats || {};
  } catch (err) {
    console.log(err);
    await setData(data);
  }
  data.chats = {};
  data.chats = {};
  data.his = {};
  await setData(data);
}

await initData();

export async function getData(): Promise<Data> {
  return data;
}

var pendding = false;
export async function setData(newData: Data): Promise<void> {
  if (pendding) {
    return;
  }
  pendding = true;
  setTimeout(() => {
    fs.writeFile("./data.json", JSON.stringify(newData));
    pendding = false;
  }, 20000);
}

export async function getCoinChats(symbol: string): Promise<string[]> {
  symbol = symbol.replace("USDT", "").replace("USDC", "");
  return Object.entries(data.coins)
    .filter(([key]) => key.startsWith(`${symbol}:`))
    .map(([key]) => key.split(":")[1]);
  // .concat(['filehelper']);
}

export async function getMyCoins(wxid: string): Promise<string[]> {
  return Object.entries(data.coins)
    .filter(([key]) => key.split(":")[1] === wxid)
    .map(([key]) => key.split(":")[0]);
}

export async function toggleCoinChat(
  symbol: string,
  wxid: string,
  status: boolean,
): Promise<void> {
  if (status) {
    data.coins[`${symbol}:${wxid}`] = true;
  } else {
    delete data.coins[`${symbol}:${wxid}`];
  }
  await setData(data);
}

export function getSettings(wxid: string, key: string) {
  return data.settings[key + "_" + wxid];
}

export async function saveSettings(wxid: string, key: string, value) {
  data.settings[key + "_" + wxid] = value;
  await setData(data);
  return data;
}

export async function toggleRegouStatus(wxid: string, status: string) {
  let s = status.trim() == "开" ? true : false;
  data.settings["regou_status_" + wxid] = s;
  await setData(data);
  return s ? "开" : "关";
}

export async function toggleBinanceStatus(wxid: string, status: string) {
  let s = status.trim() == "开" ? true : false;
  data.settings["binance_status_" + wxid] = s;
  await setData(data);
  return s ? "开" : "关";
}

export async function saveChats(wxid: string, content: string) {
  if (!data.chats[wxid]) {
    data.chats[wxid] = [];
  }
  if (data.chats[wxid].length > 20) {
    data.chats[wxid].shift();
  }
  data.chats[wxid].push(content);
  await setData(data);
}

export async function getChats(wxid: string) {
  return data.chats[wxid] || [];
}
